package acom.dhy.qigsaw2test.qigsaw

import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent

class QigsawInstaller(owner: LifecycleOwner) : LifecycleObserver {
    private val startIntentSenderForResult: ActivityResultLauncher<IntentSenderRequest>

    init {
        owner.lifecycle.addObserver(this)
        startIntentSenderForResult = when (owner) {
            is ComponentActivity -> {
                owner.registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
                    if (it.resultCode == AppCompatActivity.RESULT_CANCELED) onFailed()
                }
            }
            is Fragment -> {
                owner.registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
                    if (it.resultCode == AppCompatActivity.RESULT_CANCELED) onFailed()
                }
            }
            else -> throw IllegalArgumentException("must be ${ComponentActivity::class} or ${Fragment::class}")
        }

    }

    private fun onFailed() {
//        setResult(AppCompatActivity.RESULT_CANCELED)
//        finish()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun onCreate() {

    }
}